#include "memorywidget.h"
#include "sysinfo.h"

#include <QtCharts/QAreaSeries>
#include <QLinearGradient>
#include <QPen>

using namespace QtCharts;

const int CHART_X_RANGE_COUNT = 50;
const int CHART_X_RANGE_MAX = CHART_X_RANGE_COUNT - 1;
const int COLOR_DARK_BLUE = 0x209fdf;
const int COLOR_LIGHT_BLUE = 0xbfdfef;
const int PEN_WIDTH = 3;

MemoryWidget::MemoryWidget(QWidget* parent):
    SysInfoWidget (parent),
    m_serials(new QLineSeries(this)),
    m_point_position_x(0)
{
    QPen pen(COLOR_DARK_BLUE);
    pen.setWidth(PEN_WIDTH);

    QLinearGradient linear_gradient(QPointF(0, 0), QPointF(0, 1));
    linear_gradient.setColorAt(1.0, COLOR_DARK_BLUE);
    linear_gradient.setColorAt(0.0, COLOR_LIGHT_BLUE);
    linear_gradient.setCoordinateMode(QGradient::ObjectBoundingMode);

    QAreaSeries* area_series = new QAreaSeries(m_serials);
    area_series->setPen(pen);
    area_series->setBrush(linear_gradient);

    QChart* chart = chart_view().chart();
    chart->addSeries(area_series);
    chart->setTitle("Memory used");
    chart->createDefaultAxes();
    chart->axisX()->setVisible(false);
    chart->axisX()->setRange(0, CHART_X_RANGE_MAX);
    chart->axisY()->setRange(0, 100);
}

void MemoryWidget::update_series()
{
    double memory_used = SysInfo::instance().memory_used();
    m_serials->append(m_point_position_x++, memory_used);
    if(m_serials->count() > CHART_X_RANGE_COUNT)
    {
        QChart* chart = chart_view().chart();
        chart->scroll(chart->plotArea().width()/CHART_X_RANGE_MAX, 0);
        m_serials->remove(0);
    }
}
